package cn.com.dashihui.api.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.tx.Tx;

import cn.com.dashihui.api.base.BaseController;
import cn.com.dashihui.api.common.OrderCode;
import cn.com.dashihui.api.common.ResultMap;
import cn.com.dashihui.api.dao.Order;
import cn.com.dashihui.api.dao.OrderPayAPIRecord;
import cn.com.dashihui.api.interceptor.AuthLoginInterceptor;
import cn.com.dashihui.api.service.OrderService;
import cn.com.dashihui.kit.CommonKit;
import cn.com.dashihui.kit.DatetimeKit;
import cn.com.dashihui.kit.DoubleKit;
import cn.com.dashihui.pay.alipay.sign.SignUtils;
import cn.com.dashihui.pay.wx.kit.HttpsRequest;
import cn.com.dashihui.pay.wx.kit.Signature;
import cn.com.dashihui.pay.wx.kit.UtilKit;
import cn.com.dashihui.pay.wx.request.PreOrderReqData;
import cn.com.dashihui.pay.wx.request.QueryOrderReqData;
import cn.com.dashihui.pay.wx.response.PreOrderResData;
import cn.com.dashihui.pay.wx.response.QueryOrderResData;
@Before(AuthLoginInterceptor.class)
public class OrderController extends BaseController {

	//使用Duang.duang进行封装，使普通类具有事务的功能
	private OrderService service = Duang.duang(OrderService.class);

	/**
	 * 保存订单<br/>
	 * 在保存订单时，需要验证<br/>
	 * 1.验证所购买商品是否是“上架”状态
	 * 2.对商品数量是否超过限购数量作验证，如果不符合则保存不在成功
	 * 3.验证客户端提交过来的订单总金额和服务端计算出来的总金额是否一致
	 * @param STOREID 商铺ID
	 * @param GOODSID 商品ID
	 * @param COUNT 购买数量
	 * @param AMOUNT 总金额
	 * @param PAYTYPE 支付方式
	 * @param TAKETYPE 取货方式
	 * @param LINKNAME 联系人姓名
	 * @param SEX 性别
	 * @param TEL 电话
	 * @param ADDRESS 地址
	 * @param DESCRIBE 订单备注
	 */
	public void save(){
		String storeid = getPara("STOREID");
 		String storeGoodsIds = getPara("STOREGOODSIDS");//店铺商品IDS
 		String selfGoodsIds = getPara("SELFGOODSIDS");//自营商品IDS
		String storeCounts = getPara("STORECOUNTS");//店铺商品数量
		String selfCounts = getPara("SELFCOUNTS");//自营商品数量
		String storeAmount = getPara("STOREAMOUNT");//店铺商品总金额
		String selfAmount = getPara("SELFAMOUNT");//自营商品总金额
		String storePayType = getPara("STOREPAYTYPE");//店铺商品支付方式
		String selfPayType = getPara("SELFPAYTYPE");//自营商品支付方式
		String storeTakeType = getPara("STORETAKETYPE");//店铺商品取货方式
		String selfTakeType = getPara("SELFTAKETYPE");//自营商品取货方式
		String linkName = getPara("LINKNAME");
		String sex = getPara("SEX");
		String tel = getPara("TEL");
		String address = getPara("ADDRESS");
		String describe = getPara("DESCRIBE");
		int isRedeem = getParaToInt("ISREDEEM",0);
		
		if(StrKit.isBlank(storeid)){
			renderFailed("参数STOREID不能为空");
    		return;
		}else if(StrKit.isBlank(storeGoodsIds) && StrKit.isBlank(selfGoodsIds)){
			renderFailed("参数STOREGOODSIDS和SELFGOODSIDS不能同时为空");
    		return;
		}else if(StrKit.isBlank(linkName)){
			renderFailed("参数LINKNAME不能为空");
    		return;
		}else if(StrKit.isBlank(sex)){
			renderFailed("参数SEX不能为空");
    		return;
		}else if(StrKit.isBlank(tel)){
			renderFailed("参数TEL不能为空");
    		return;
		}else if(StrKit.isBlank(address)){
			renderFailed("参数ADDRESS不能为空");
    		return;
		}else if(!StrKit.isBlank(describe)&&describe.length()>=200){
			renderFailed("参数DESCRIBE内容过长");
    		return;
		}else{
			//店铺商品不为空，自营商品为空
			if(!StrKit.isBlank(storeGoodsIds) && StrKit.isBlank(selfGoodsIds)){
				if(StrKit.isBlank(storeCounts)){
					renderFailed("参数STORECOUNTS不能为空");
					return;
				}else if(StrKit.isBlank(storeAmount)){
					renderFailed("参数STOREAMOUNT不能为空");
					return;
				}else if(StrKit.isBlank(storePayType)){
					renderFailed("参数STOREPAYTYPE不能为空");
					return;
				}else if(StrKit.isBlank(storeTakeType)){
					renderFailed("参数STORETAKETYPE不能为空");
					return;
				}
				/**
				 * 验证用户要购买的店铺商品
				 * 1.验证是否有商品已下架
				 * 2.验证是否有商品购买量已经超过了今日所限量
				 * 3.验证总金额是否与客户端的入参总金额相同
				 */
				int validateStoreGoods = service.validate(getCurrentUser().getInt("id"),Integer.valueOf(storeid),storeGoodsIds,storeCounts,storeAmount);
				if(validateStoreGoods==1){
					renderFailed("您所购买的便利店商品中有已下架的商品");
					return;
				}else if(validateStoreGoods==2){
					renderFailed("您所购买的便利店商品中有超出限量的商品");
					return;
				}else if(validateStoreGoods==3){
					renderFailed("总金额计算不正确");
					return;
				}
				//生成店铺服务类订单的订单编号，以大写字母G开头
				String storeOrderNum = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				//保存店铺商品订单
				Order storeOrder = new Order()
						.set("orderNum", storeOrderNum)
						.set("from", OrderCode.OrderFrom.APP)
						.set("storeid", storeid)
						.set("userid", getCurrentUser().getInt("id"))
						.set("amount", storeAmount)
						.set("payType", Integer.valueOf(storePayType).intValue())
						.set("payState", OrderCode.OrderPayState.NO_PAY)
						.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
						.set("orderState", OrderCode.OrderState.NORMAL)
						.set("takeType", Integer.valueOf(storeTakeType).intValue())
						.set("deliverType", OrderCode.OrderDeliverType.ON_STORE)
						.set("linkName", linkName)
						.set("sex", sex)
						.set("tel", tel)
						.set("address", address)
						.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
						.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
						.set("isSelf", "0");
				//用户如填写了备注，则记录
				if(StrKit.notBlank(describe)){
					storeOrder.set("describe", describe);
				}
				int forwardFlag = 0;
				try {
					forwardFlag = service.doRedeem(storeOrder,null,storeGoodsIds,selfGoodsIds,storeCounts,selfCounts,getCurrentUser().getInt("id"),isRedeem);
				} catch (Exception e) {
					e.printStackTrace();
					renderFailed("保存订单失败");
					return;
				}
				renderSuccess(ResultMap.newInstance().put("ORDERNUM",storeOrderNum).put("AMOUNT", storeAmount).put("FORWARDFLAG", forwardFlag));
			//店铺商品为空，自营商品不为空
			}else if(StrKit.isBlank(storeGoodsIds) && !StrKit.isBlank(selfGoodsIds)){
				if(StrKit.isBlank(selfCounts)){
					renderFailed("参数SELFCOUNTS不能为空");
					return;
				}else if(StrKit.isBlank(selfAmount)){
					renderFailed("参数SELFAMOUNT不能为空");
					return;
				}else if(StrKit.isBlank("selfTakeType")){
					renderFailed("参数SELFTAKETYPE不能为空");
					return;
				}else if(StrKit.isBlank("selfTakeType")){
					renderFailed("参数SELFTAKETYPE不能为空");
					return;
				}
				/**
				 * 验证用户要购买的自营商品
				 * 1.验证是否有商品已下架
				 * 2.验证是否有商品购买量已经超过了今日所限量
				 * 3.验证总金额是否与客户端的入参总金额相同
				 */
				int validateSelfGoods = service.validate(getCurrentUser().getInt("id"),Integer.valueOf(storeid),selfGoodsIds,selfCounts,selfAmount);
				if(validateSelfGoods==1){
					renderFailed("您所购买的大实惠自营商品中有已下架的商品");
					return;
				}else if(validateSelfGoods==2){
					renderFailed("您所购买的大实惠自营商品中有超出限量的商品");
					return;
				}else if(validateSelfGoods==3){
					renderFailed("总金额计算不正确");
					return;
				}
				//生成自营服务类订单的订单编号，以大写字母G开头
				String selfOrderNum = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				//保存自营商品订单
				Order selfOrder = new Order()
						.set("orderNum", selfOrderNum)
						.set("from", OrderCode.OrderFrom.APP)
						.set("userid", getCurrentUser().getInt("id"))
						.set("amount", selfAmount)
						.set("payType", Integer.valueOf(selfPayType).intValue())
						.set("payState", OrderCode.OrderPayState.NO_PAY)
						.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
						.set("orderState", OrderCode.OrderState.NORMAL)
						.set("takeType", Integer.valueOf(selfTakeType).intValue())
						.set("deliverType", OrderCode.OrderDeliverType.ON_LOGISTICS)
						.set("linkName", linkName)
						.set("sex", sex)
						.set("tel", tel)
						.set("address", address)
						.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
						.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
						.set("isSelf", "1");
				//用户如填写了备注，则记录
				if(StrKit.notBlank(describe)){
					selfOrder.set("describe", describe);
				}
				int forwardFlag = 0;
				try {
					forwardFlag = service.doRedeem(null,selfOrder,storeGoodsIds,selfGoodsIds,storeCounts,selfCounts,getCurrentUser().getInt("id"),isRedeem);
				} catch (Exception e) {
					e.printStackTrace();
					renderFailed("保存订单失败");
					return;
				}
				renderSuccess(ResultMap.newInstance().put("ORDERNUM",selfOrderNum).put("AMOUNT", storeAmount).put("FORWARDFLAG", forwardFlag));
			//店铺和自营商品都不为空
			}else if(!StrKit.isBlank(storeGoodsIds) && !StrKit.isBlank(selfGoodsIds)){
				if(StrKit.isBlank(storeCounts)||StrKit.isBlank(selfCounts)){
					renderFailed("参数COUNTS不能为空");
					return;
				}else if(StrKit.isBlank(storeAmount)||StrKit.isBlank(selfAmount)){
					renderFailed("参数AMOUNT不能为空");
					return;
				}else if(StrKit.isBlank(storePayType)||StrKit.isBlank(selfPayType)){
					renderFailed("参数PAYTYPE不能为空");
					return;
				}else if(StrKit.isBlank(storeTakeType)||StrKit.isBlank(selfTakeType)){
					renderFailed("参数TAKETYPE不能为空");
					return;
				}
				//生成店铺服务类订单的订单编号，以大写字母G开头
				String orderNumStore = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				//生成自营服务类订单的订单编号，以大写字母G开头
				String orderNumSelf = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				//生成服务类订单的合单编号，以大写字母G开头
				String mergerNum = "G"+DatetimeKit.getFormatDate("yyyyMMddHHmmssSSS")+CommonKit.randomNum(3);
				/**
				 * 验证用户要购买的店铺商品
				 * 1.验证是否有商品已下架
				 * 2.验证是否有商品购买量已经超过了今日所限量
				 * 3.验证总金额是否与客户端的入参总金额相同
				 */
				int validateStoreGoods = service.validate(getCurrentUser().getInt("id"),Integer.valueOf(storeid),storeGoodsIds,storeCounts,storeAmount);
				if(validateStoreGoods==1){
					renderFailed("您所购买的便利店商品中有已下架的商品");
					return;
				}else if(validateStoreGoods==2){
					renderFailed("您所购买的便利店商品中有超出限量的商品");
					return;
				}else if(validateStoreGoods==3){
					renderFailed("总金额计算不正确");
					return;
				}
				//保存店铺订单
				Order storeOrder = new Order()
						.set("orderNum", orderNumStore)
						.set("from", OrderCode.OrderFrom.APP)
						.set("storeid", storeid)
						.set("userid", getCurrentUser().getInt("id"))
						.set("amount", storeAmount)
						.set("payType", Integer.valueOf(storePayType).intValue())
						.set("payState", OrderCode.OrderPayState.NO_PAY)
						.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
						.set("orderState", OrderCode.OrderState.NORMAL)
						.set("takeType", Integer.valueOf(storeTakeType).intValue())
						.set("deliverType", OrderCode.OrderDeliverType.ON_STORE)
						.set("linkName", linkName)
						.set("sex", sex)
						.set("tel", tel)
						.set("address", address)
						.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
						.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
						.set("isSelf", "0")
						.set("mergerNum", mergerNum);
				/**
				 * 验证用户要购买的自营商品
				 * 1.验证是否有商品已下架
				 * 2.验证是否有商品购买量已经超过了今日所限量
				 * 3.验证总金额是否与客户端的入参总金额相同
				 */
				int validateSelfGoods = service.validate(getCurrentUser().getInt("id"),Integer.valueOf(storeid),selfGoodsIds,selfCounts,selfAmount);
				if(validateSelfGoods==1){
					renderFailed("您所购买的大实惠自营商品中有已下架的商品");
					return;
				}else if(validateSelfGoods==2){
					renderFailed("您所购买的大实惠自营商品中有超出限量的商品");
					return;
				}else if(validateSelfGoods==3){
					renderFailed("总金额计算不正确");
					return;
				}
				//保存自营商品订单
				Order selfOrder = new Order()
						.set("orderNum", orderNumSelf)
						.set("from", OrderCode.OrderFrom.APP)
						.set("userid", getCurrentUser().getInt("id"))
						.set("amount", selfAmount)
						.set("payType", Integer.valueOf(selfPayType).intValue())
						.set("payState", OrderCode.OrderPayState.NO_PAY)
						.set("deliverState", OrderCode.OrderDeliverState.NO_DELIVER)
						.set("orderState", OrderCode.OrderState.NORMAL)
						.set("takeType", Integer.valueOf(selfTakeType).intValue())
						.set("deliverType", OrderCode.OrderDeliverType.ON_LOGISTICS)
						.set("linkName", linkName)
						.set("sex", sex)
						.set("tel", tel)
						.set("address", address)
						.set("startDate", DatetimeKit.getFormatDate("yyyy-MM-dd HH:mm:ss"))
						.set("expireDate",  DatetimeKit.getIntervalFormatDate(PropKit.getInt("constants.order.interval"), "yyyy-MM-dd HH:mm:ss"))
						.set("isSelf", "1")
						.set("mergerNum", mergerNum);
				//用户如填写了备注，则记录
				if(StrKit.notBlank(describe)){
					storeOrder.set("describe", describe);
					selfOrder.set("describe", describe);
				}
				int forwardFlag = 0;
				try {
					forwardFlag = service.doRedeem(storeOrder,selfOrder,storeGoodsIds,selfGoodsIds,storeCounts,selfCounts,getCurrentUser().getInt("id"),isRedeem);
				} catch (Exception e) {
					e.printStackTrace();
					renderFailed("保存订单失败");
					return;
				}
				renderSuccess(ResultMap.newInstance().put("ORDERNUM",mergerNum).put("AMOUNT", storeAmount).put("FORWARDFLAG", forwardFlag));
			}
		}
	}
	
	/**
	 * 客户端确认去支付<br/>
	 * 首先验证支付方式参数，并验证根据订单号查询订单记录是否存在，以此验证订单号是否正确<br/>
	 * 然后根据所选择的支付方式，向不同平台发起支付请求<br/>
	 * 目前只申请了微信支付平台，2015/12/02
	 * @param ORDERNUM 要支付的订单号
	 * @param FLAG 用户所选择的支付方式，1:微信支付
	 */
	public void pay(){
		String orderNum = getPara("ORDERNUM");
		String flagStr = getPara("FLAG");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(StrKit.isBlank(flagStr)){
			renderFailed("参数FLAG不能为空");
    		return;
		}else if(!flagStr.equals(String.valueOf(OrderCode.OrderPayMethod.WEIXIN))&&!flagStr.equals(String.valueOf(OrderCode.OrderPayMethod.ALIPAY))){
			renderFailed("参数FLAG不正确");
    		return;
		}
		//查询订单详情并以此验证订单号
		List<Order> orderList = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
		if(orderList==null || orderList.size() <= 0){
			renderFailed("订单不存在");
    		return;
		}
		//验证订单是否有效
		String startDate = DatetimeKit.getFormatDate(orderList.get(0).getDate("startDate"),"yyyyMMddHHmmss");
		String expireDate = DatetimeKit.getFormatDate(orderList.get(0).getDate("expireDate"),"yyyyMMddHHmmss");
		if(DatetimeKit.compareDate(orderList.get(0).getDate("expireDate")) == -1){
			renderFailed("您的订单已过期");
			return;
		}
		//计算订单总金额
		double amount = 0;
		for(int i = 0; i < orderList.size(); i++){
			double orderAmount = orderList.get(i).get("amount");
			amount = DoubleKit.add(amount, orderAmount);
		}
		
		//根据用户所选择的支付方式不同作不同处理
		int payMethod = Integer.valueOf(flagStr);
		if(payMethod == OrderCode.OrderPayMethod.WEIXIN){
			//1：微信支付
			//获取客户端IP
			String remoteip = CommonKit.getClientIp(getRequest());
			//获取订单总金额，并转换为以“分”为单位
			String amountStr = String.valueOf(Double.valueOf(DoubleKit.mul(amount,100)).intValue()).toString();
			//向微信发起预支付请求
			PreOrderReqData preOrderReqData = new PreOrderReqData("大实惠云商超市",orderNum,amountStr,remoteip,PropKit.get("weixinpay.goodsOrderNotifyUrl"),startDate,expireDate);
			PreOrderResData preOrderRspData = null;
			try {
				preOrderRspData = (PreOrderResData)UtilKit.getObjectFromXML(new HttpsRequest().post(PropKit.get("weixinpay.unifiedorder"), preOrderReqData), PreOrderResData.class);
			}catch(Exception e){
				e.printStackTrace();
				renderFailed("支付错误");
	    		return;
			}
			//预支付完成
			if(preOrderRspData!=null){
				//保存接口请求记录
				String sendContent = UtilKit.getXMLFromObject(preOrderReqData);
				String returnContent = UtilKit.getXMLFromObject(preOrderRspData);
				logger.info(sendContent);
				logger.info(returnContent);
				new OrderPayAPIRecord().set("orderNum", orderNum)
					.set("sendContent", sendContent)
					.set("returnContent", returnContent)
					.set("payMethod", payMethod)
					.set("flag", 1)
					.save();
				if(preOrderRspData.getReturn_code().equals("SUCCESS")&&preOrderRspData.getResult_code().equals("SUCCESS")){
					//更新订单支付方式为微信
					for(int i = 0; i < orderList.size(); i++){
						Order record = orderList.get(i);
						record.set("payMethod", OrderCode.OrderPayMethod.WEIXIN).update();
					}
					//向客户端返回结果
					String noncestr = CommonKit.getRandomStringByLength(32);
					String timestamp = DatetimeKit.getTimestamp();
					renderSuccess(ResultMap.newInstance()
							.put("APPID", preOrderReqData.getAppid())
							.put("PARTNERID", preOrderReqData.getMch_id())
							.put("PREPAYID", preOrderRspData.getPrepay_id())
							.put("PACKAGE", "Sign=WXPay")
							.put("NONCESTR", noncestr)
							.put("TIMESTAMP", timestamp)
							.put("SIGN", Signature.getSign(ResultMap.newInstance()
									.put("appid", preOrderReqData.getAppid())
									.put("partnerid", preOrderReqData.getMch_id())
									.put("prepayid", preOrderRspData.getPrepay_id())
									.put("package", "Sign=WXPay")
									.put("noncestr", noncestr)
									.put("timestamp", timestamp).getAttrs())));
					return;
				}
			}
		}else if(payMethod == OrderCode.OrderPayMethod.ALIPAY){
			//2：支付宝支付
			//接收客户端入参
			StringBuffer params = new StringBuffer();
			// 签约合作者身份ID
			params.append("partner=\"").append(PropKit.get("alipay.partner")).append("\"");
			// 签约卖家支付宝账号
			params.append("&seller_id=\"").append(PropKit.get("alipay.seller_id")).append("\"");
			// 商户网站唯一订单号
			params.append("&out_trade_no=\"").append(orderNum).append("\"");
			// 商品名称
			params.append("&subject=\"大实惠云商超市\"");
			// 商品详情
			params.append("&body=\"大实惠云商超市\"");
			// 商品金额
			params.append("&total_fee=\"").append(amount).append("\"");
			// 服务器异步通知页面路径
			params.append("&notify_url=\"").append(PropKit.get("alipay.goodsOrderNotifyUrl")).append("\"");
			// 服务接口名称， 固定值
			params.append("&service=\"mobile.securitypay.pay\"");
			// 支付类型， 固定值
			params.append("&payment_type=\"1\"");
			// 参数编码， 固定值
			params.append("&_input_charset=\"utf-8\"");
			// 设置未付款交易的超时时间，可空
			// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
			// 取值范围：1m～15d。
			// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
			// 该参数数值不接受小数点，如1.5h，可转换为90m。
			// 或者使用绝对时间（示例格式：2014-06-13 16:00:00）。
			// m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。
			// 该参数数值不接受小数点，如1.5h，可转换为90m。
			params.append("&it_b_pay=\"").append(DatetimeKit.getFormatDate(orderList.get(0).getDate("expireDate"),"yyyy-MM-dd HH:mm:ss")).append("\"");
			//签名并作URL编码
			String sign = SignUtils.sign(params.toString(),PropKit.get("alipay.privateKey"));
			try {
				sign = URLEncoder.encode(sign, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			params.append("&sign=\"").append(sign).append("\"");
			params.append("&sign_type=\"RSA\"");
			//更新订单支付方式为支付宝
			for(int i = 0; i < orderList.size(); i++){
				Order record = orderList.get(i);
				record.set("payMethod", OrderCode.OrderPayMethod.ALIPAY).update();
			}
			//将结果返回给客户端
			renderSuccess(ResultMap.newInstance().put("PARAMS", params.toString()).getAttrs());
			return;
		}
		renderFailed("支付错误");
		return;
	}
	
	/**
	 * 查询指定订单支付结果<br/>
	 * 客户端跳转向微信或其他第三方支付平台，在支付完成后，第三方平台会返回客户端界面，并告知支付结果，此时客户端需要再次向服务端发起支付结果查询请求
	 * @param ORDERNUM 订单号
	 * @param PAYSTATE 支付结果，1:已支付，0:未支付
	 */
	public void query(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}
		//查询订单列表，并验证订单是否存在，以及订单支付状态
		List<Order> orderList = service.getOrderListByMergerOrderNum(getCurrentUser().getInt("id"),orderNum);
		if(orderList==null||orderList.size()==0){
			renderFailed("订单不存在");
    		return;
		}
		//依次判断订单支付状态
		for(Order order : orderList){
			if(order.getInt("payType")==OrderCode.OrderPayType.ON_LINE&&order.getInt("payState")==OrderCode.OrderPayState.NO_PAY){
				//如果状态为未支付，则调用相应支付平台的接口进行再次验证
				if(order.getInt("payMethod")==OrderCode.OrderPayMethod.WEIXIN){
					//1：微信支付
					try {
						QueryOrderReqData queryOrderReqData = new QueryOrderReqData(order.getStr("tradeNo"));
						String responseStr = new HttpsRequest().post(PropKit.get("weixinpay.orderquery"), queryOrderReqData);
						QueryOrderResData queryOrderResData = (QueryOrderResData) UtilKit.getObjectFromXML(responseStr, QueryOrderResData.class);
						if(queryOrderResData!=null){
							//保存接口请求记录
							new OrderPayAPIRecord().set("orderNum", orderNum)
							.set("sendContent", UtilKit.getXMLFromObject(queryOrderReqData))
							.set("returnContent", UtilKit.getXMLFromObject(queryOrderResData))
							.set("payMethod", OrderCode.OrderPayMethod.WEIXIN)
							.set("flag", 3)
							.save();
							if(!queryOrderResData.getReturn_code().equals("SUCCESS")||!queryOrderResData.getResult_code().equals("SUCCESS")){
								renderSuccess(ResultMap.newInstance().put("PAYSTATE", 0));
								return;
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}else if(order.getInt("payMethod")==OrderCode.OrderPayMethod.ALIPAY){
					//2：支付宝支付不提供相应的查询状态功能，以数据库订单状态为准
					renderSuccess(ResultMap.newInstance().put("PAYSTATE", 0));
					return;
				}
			}
		}
		renderSuccess(ResultMap.newInstance().put("PAYSTATE", 1));  
		return;
	}
	
	/**
	 * 查询订单列表
	 * @param APIVERSION 服务端接口版本号，以此判断来兼容旧版本接口
	 * @param FLAG 订单状态，0：全部，1:待付款，2：待发货，3：待收货，4：已完成
	 * @param FLAG 订单状态，1：全部，2:待付款，3：待收货，4：待评价，V1.3.2版本启用
	 * @param PAGENUM 页码
	 * @param PAGESIZE 数量
	 */
	public void list(){
		String apiVersion = getPara("APIVERSION");
		String storeid = getPara("STOREID");
		int pageNum = getParaToInt("PAGENUM",1);
		int pageSize = getParaToInt("PAGESIZE",PropKit.getInt("constants.pageSize"));
		int flag = getParaToInt("FLAG",0);
		if(StrKit.isBlank(storeid)){
			renderFailed("参数STOREID不能为空");
			return;
		}else{
			Page<Record> page = null;
			if(StrKit.isBlank(apiVersion)||apiVersion.equals(PropKit.get("api.version.132"))||apiVersion.equals(PropKit.get("api.version.133"))){
				//1.3.2版本新增代码，2016-03-16
				page = service.findByPage_v132(Integer.valueOf(storeid),getCurrentUser().getInt("id"),flag,pageNum,pageSize);
			}else{
				//1.3.2版本前代码，2016-03-16
				page = service.findByPage(Integer.valueOf(storeid),getCurrentUser().getInt("id"),flag,pageNum,pageSize);
			}
			if(page!=null){
				//查询订单的商品列表供页面展示
				service.getOrderGoodsList(page.getList());
				renderSuccess(ResultMap.newInstance()
						.put("PAGENUMBER", page.getPageNumber())
						.put("PAGESIZE", page.getPageSize())
						.put("TOTALPAGE", page.getTotalPage())
						.put("TOTALROW", page.getTotalRow())
						.put("LIST", page.getList()));
			}else{
				renderSuccess(ResultMap.newInstance()
						.put("PAGENUMBER", pageNum)
						.put("PAGESIZE", pageSize)
						.put("TOTALPAGE", 0)
						.put("TOTALROW", 0)
						.put("LIST", null));
			}
		}
	}
	
	/**
	 * 查询退款订单列表
	 */
	public void refund() {
		int pageNum = getParaToInt("pageNum",1);
		String storeid = getPara("STOREID");
		int pageSize = getParaToInt("pageSize", PropKit.getInt("constants.pageSize"));
		Page<Record> page = service.findRefundByPage(Integer.valueOf(storeid), getCurrentUser().getInt("id"), pageNum, pageSize);
		if(page!=null){
			//查询订单的商品列表供页面展示
			service.getOrderGoodsList(page.getList());
			renderSuccess(ResultMap.newInstance()
					.put("PAGENUMBER", page.getPageNumber())
					.put("PAGESIZE", page.getPageSize())
					.put("TOTALPAGE", page.getTotalPage())
					.put("TOTALROW", page.getTotalRow())
					.put("LIST", page.getList())
					.put("STATEMENT", PropKit.get("constants.refund.statement")));
		}
		return;
	}
	
	/**
	 * 取消订单
	 * @param ORDERNUM 订单号
	 * @param REASON 取消订单理由
	 */
	@Before(Tx.class)
	public void cancel(){
		String orderNum = getPara("ORDERNUM");
		String reason = getPara("REASON");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许取消");
					return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int packState = order.getInt("packState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，打包状态为“未接单”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(packState!=OrderCode.OrderPackState.NO_ACCEPT){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，打包状态为“未接单”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					if(packState!=OrderCode.OrderPackState.NO_ACCEPT){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.3.货到付款+送货上门时，发货状态为“未发货”时可取消订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许取消");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，无限制
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					
				}
				try {
					//在service中进行取消订单(修改订单状态、生成退款订单)的一系列操作,保证事务回滚
					service.cancelOrder(order,reason,payType,payState,orderNum);
					renderSuccess(order);
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//3.其他情况
				renderFailed("取消订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 删除订单
	 * @param ORDERNUM 订单号
	 */
	public void delete(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“取消”、“过期”、“完成”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.CANCEL&&orderState!=OrderCode.OrderState.EXPIRE&&orderState!=OrderCode.OrderState.FINISH){
					renderFailed("此订单当前不允许删除");
		    		return;
				}
				//2.删除订单操作，并记录日志
				order.set("orderState", OrderCode.OrderState.DELETE);
				if(order.update()){
					service.log(order.getStr("orderNum"),OrderCode.OrderLogType.DELETE,"用户", OrderCode.OrderLogType.DELETE_ACTION, "订单已删除");
					renderSuccess();
					return;
				}
				//3.其他情况
				renderFailed("删除订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 签收
	 * @param ORDERNUM 订单号
	 */
	public void receive(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许签收");
		    		return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“已发货”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(payState!=OrderCode.OrderPayState.HAD_PAY&&deliverState!=OrderCode.OrderDeliverState.HAD_DELIVER){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，支付状态为“已付款”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					if(payState!=OrderCode.OrderPayState.HAD_PAY){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.3.货到付款+送货上门时，发货状态为“已发货”时可签收订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.HAD_DELIVER){
						renderFailed("此订单当前不允许签收");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，无限制
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					
				}
				//3.签收订单操作，并记录日志
				try {
					//在service中进行订单签收(修改订单状态、商品返利、用户是否升级为黄金会员)的一系列操作,保证事务回滚
					service.receiveOrder(order,getCurrentUser());
					renderSuccess();
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}
				//4.其他情况
				renderFailed("签收订单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}

	/**
	 * 用户催单
	 * @param ORDERNUM 订单号
	 */
	public void urge(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//1.判断订单状态是否为“正常”状态
				int orderState = order.getInt("orderState");
				if(orderState!=OrderCode.OrderState.NORMAL){
					renderFailed("此订单当前不允许催单");
		    		return;
				}
				//2.根据订单不同状态进行不同操作
				int payType = order.getInt("payType");
				int payState = order.getInt("payState");
				int takeType = order.getInt("takeType");
				int deliverState = order.getInt("deliverState");
				//2.1.在线支付+送货上门，支付状态为“已付款”，发货状态为“未发货”时可催单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(payState!=OrderCode.OrderPayState.HAD_PAY&&deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许催单");
			    		return;
					}
				}else
				//2.2.在线支付+门店自取，不允许催单
				if(payType==OrderCode.OrderPayType.ON_LINE&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					renderFailed("此订单当前不允许催单");
		    		return;
				}else
				//2.3.货到付款+送货上门时，发货状态为“未发货”时可催单订单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.DELIVER){
					if(deliverState!=OrderCode.OrderDeliverState.NO_DELIVER){
						renderFailed("此订单当前不允许催单");
			    		return;
					}
				}else
				//2.4.货到付款+门店自取时，不允许催单
				if(payType==OrderCode.OrderPayType.ON_DELIVERY&&takeType==OrderCode.OrderTakeType.TAKE_SELF){
					renderFailed("此订单当前不允许催单");
		    		return;
				}
				//3.催单操作
				int urgeTimes = order.getInt("urgeTimes");
				if(urgeTimes==0){
					//首次催单需要在下单xx分钟后
					Date orderDate = order.getDate("createDate");
					Date now = new Date();
					int diffMin = (int)(now.getTime()-orderDate.getTime())/(1000*60);
					if(diffMin<=PropKit.getInt("constants.order.urgeFirstTime")){
						renderFailed("您的订单正在加急处理中，请耐心等待");
						return;
					}
				}else{
					//第二次以后催单，间隔需要大于xx分钟
					Date urgeLastTimeDate = order.getDate("urgeLastTime");
					Date now = new Date();
					int diffMin = (int)(now.getTime()-urgeLastTimeDate.getTime())/(1000*60);
					if(diffMin<=PropKit.getInt("constants.order.urgePerTime")){
						renderFailed("您的订单正在加急处理中，请耐心等待");
						return;
					}
				}
				try {
					//催单，修改催单累计次数加1，更新最后一次催单记录时间
					order = service.urgeOrder(getCurrentUser().getInt("id"),orderNum);
					urgeTimes = order.getInt("urgeTimes");
					String urgeLastTime = DatetimeKit.getFormatDate(order.getDate("urgeLastTime"),"yyyy-MM-dd HH:mm:ss");
					//记录日志
					service.log(orderNum,OrderCode.OrderLogType.URGE,"用户",OrderCode.OrderLogType.URGE_ACTION,"第"+order.getInt("urgeTimes")+"次催单，催单时间："+urgeLastTime);
					//返回客户端
					renderSuccess(ResultMap.newInstance().put("TIMES", urgeTimes).put("DATETIME", urgeLastTime));
					return;
				} catch (Exception e) {
					e.printStackTrace();
				}

				//4.其他情况
				renderFailed("催单失败");
				return;
			}else{
				renderFailed("订单不存在！");
				return;
			}
		}
	}
	
	/**
	 * 查询订单详情，及订单商品列表<br/>
	 * 注意，查询订单时，只查询订单状态“正常”、“已完成”、“已取消”的
	 * @param ORDERNUM 订单号
	 */
	public void detail(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//查询订单的商品清单列表
				order.put("GOODSLIST", service.getGoodsListByOrderNum(orderNum));
				//判断如果当前订单支付方式为在线支付，且未支付时，从下单时间计算出目前还有多久过期
				if(order.getInt("orderState")==OrderCode.OrderState.NORMAL&&order.getInt("PAYTYPE")==OrderCode.OrderPayType.ON_LINE&&order.getInt("PAYSTATE")==OrderCode.OrderPayState.NO_PAY){
					long startTimestamp = order.getTimestamp("STARTDATE").getTime();
					long nowTimestamp = System.currentTimeMillis();
					//判断从下单到当前的时间，再加上5秒（此为客户端请求服务端的接口延迟时间），如果小于订单过期时间，则将该数字回传给客户端
					if(nowTimestamp-startTimestamp+5*1000<PropKit.getLong("constants.order.interval")){
						//计算出离过期还剩余的毫秒数返回给客户端
						order.put("REMAIN",PropKit.getLong("constants.order.interval")-(nowTimestamp-startTimestamp));
					}else{
						//相反，则认为订单已过期，修改订单状态返回给客户端
						order.set("ORDERSTATE", OrderCode.OrderState.EXPIRE);
					}
				}
				renderSuccess(order);
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 查询订单操作日志列表<br/>
	 * @param ORDERNUM 订单号
	 */
	public void track(){
		String orderNum = getPara("ORDERNUM");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				//查询订单的操作日志列表
				renderSuccess(service.getLogListByOrderNum(orderNum));
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
	
	/**
	 * 对订单进行评价
	 * @param ORDERNUM 订单号
	 * @param EVAL1 商品满意度
	 * @param EVAL2 配送速度满意度
	 * @param EVAL3 服务质量满意度
	 * @param CONTENT 评价内容
	 */
	public void eval(){
		String orderNum = getPara("ORDERNUM");
		int eval1 = getParaToInt("EVAL1",1);
		int eval2 = getParaToInt("EVAL2",1);
		int eval3 = getParaToInt("EVAL3",1);
		String content = getPara("CONTENT");
		if(StrKit.isBlank(orderNum)){
			renderFailed("参数ORDERNUM不能为空");
    		return;
		}else if(!StrKit.isBlank(content)&&content.length()>=500){
			renderFailed("参数CONTENT过长");
    		return;
		}else{
			Order order = service.getOrderByOrderNum(getCurrentUser().getInt("id"),orderNum);
			if(order!=null){
				if(service.doEval(orderNum, getCurrentUser().getInt("id"), eval1, eval2, eval3, content)){
					//更新订单评价状态为1：已评价
					order.set("evalState", 1).update();
					renderSuccess();
					return;
				}
				renderFailed("评价失败");
				return;
			}else{
				renderFailed("此订单不存在");
				return;
			}
		}
	}
}
